using System;
using System.Linq;
using System.Drawing.Drawing2D;
using System.Data;
using System.Data.Odbc;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Reviewer.Entities;
using Reviewer.Entities.Services;
using Reviewer.Business;

public partial class V2Controls_Top10Spil : System.Web.UI.UserControl
{
    private delegate Game[] LoadGamesDelegate();
    private LoadGamesDelegate loadHandler;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Page.AddOnPreRenderCompleteAsync(
                new BeginEventHandler(this.BeginAsyncLoad),
                new EndEventHandler(this.EndAsyncLoad)
                );
        }
    }

    private IAsyncResult BeginAsyncLoad(object sender, EventArgs e, AsyncCallback cb, object state)
    {
        this.loadHandler = new LoadGamesDelegate(LoadGames);
        return this.loadHandler.BeginInvoke(cb, state);
    }

    private void EndAsyncLoad(IAsyncResult ar)
    {
        this.uiRepGames.DataSource = this.loadHandler.EndInvoke(ar);
        this.uiRepGames.DataBind();
    }

    private Game[] LoadGames()
    {
        using (IGameService gameService = ServiceFactory.GameService)
        {
            return gameService.GetAll().GroupBy(t => t.GameId).Select(t => t.First()).OrderByDescending(t => t.Id).Take(10).ToArray();
        }
    }

    protected void uiRepGames_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Game game = e.Item.DataItem as Game;
            HyperLink link = e.Item.FindControl("uiHlGame") as HyperLink;
            Literal title = e.Item.FindControl("uiLitTitle") as Literal;
            Literal genre = e.Item.FindControl("uiLitGenre") as Literal;

            using (IMetadataService<Genre> genreService = ServiceFactory.GetMetadataService<Genre>())
            {
                Genre currentGenre = genreService.GetAll().FirstOrDefault(t => t.Id.Equals(game.Genre));

                link.NavigateUrl = UrlUtillity.GetGameUri(game);

                title.Text = (game.Title.Length > 30) ? game.Title.Substring(0, 30) + "..." : game.Title;
                genre.Text = (currentGenre == null) ? "Ukendt genre" : currentGenre.Name;
            }
        }
    }

}
